package com.hanxiaozhang.redis.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈Redis基础工具类〉
 *
 * @author hanxinghua
 * @create 2021/4/6
 * @since 1.0.0
 */
@Slf4j
@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;



    /**
     * 设置key
     *
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }


    /**
     * 设置带过期时间key
     *
     * @param key
     * @param value
     * @param timeout
     * @param timeUnit
     */
    public void set(String key, String value, int timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }


    /**
     * 获取key
     *
     * @param key
     * @return
     */
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }


    /**
     * 设置过期时间
     *
     * @param key
     * @param timeout
     * @param timeUnit
     */
    public void setExpire(String key, int timeout, TimeUnit timeUnit) {
        redisTemplate.expire(key, timeout, timeUnit);
    }


    /**
     * 获取过期时间
     *
     * @param key
     * @return
     */
    public Integer getExpireOnSecond(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS).intValue();
    }


    /**
     * 获取过期时间
     *
     * @param key
     * @param timeUnit
     * @return
     */
    public Long getExpire(String key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }


    /**
     * 判断key是否存在过期时间
     *
     * @param key
     * @return
     */
    public boolean isExpire(String key) {
        return getExpire(key, TimeUnit.MILLISECONDS) > 1 ? false : true;
    }


    /**
     * 判断key是否存在
     *
     * @param key
     * @return
     */
    public boolean isKey(String key) {
        return redisTemplate.hasKey(key);
    }


    /**
     * 删除key
     *
     * @param key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }


}
